package com.smartboot.plus.features;


import com.smartboot.plus.features.acl.MqttAclFeatures;
import com.smartboot.plus.features.auth.MqttAuthFeatures;
import org.smartboot.socket.extension.plugins.AbstractPlugin;
import org.smartboot.socket.transport.AioSession;
import tech.smartboot.feat.cloud.annotation.Autowired;
import tech.smartboot.feat.cloud.annotation.Bean;
import tech.smartboot.feat.cloud.annotation.PostConstruct;
import tech.smartboot.feat.core.common.logging.Logger;
import tech.smartboot.feat.core.common.logging.LoggerFactory;
import tech.smartboot.mqtt.common.enums.MqttMessageType;
import tech.smartboot.mqtt.common.message.MqttConnectMessage;
import tech.smartboot.mqtt.common.message.MqttMessage;
import tech.smartboot.mqtt.common.message.MqttVariableHeader;
import tech.smartboot.mqtt.plugin.spec.BrokerContext;

@Bean
public class MqttMessageFeatures {
    private static final Logger LOGGER = LoggerFactory.getLogger(MqttMessageFeatures.class);



    @Autowired
    private BrokerContext brokerContext;


    @Autowired
    private MqttAuthFeatures mqttAuthFeatures;


    @Autowired
    private MqttAclFeatures mqttAclFeatures;


    @PostConstruct
    public void init() {

        brokerContext.Options().addPlugin(new AbstractPlugin<MqttMessage>() {
            @Override
            public boolean preProcess(AioSession session, MqttMessage message) {
                MqttMessageType messageType = message.getFixedHeader().getMessageType();
                MqttVariableHeader variableHeader = message.getVariableHeader();

                switch (messageType) {
                    case CONNECT:
                        //处理连接认证消息
                        return mqttAuthFeatures.connectMessage(session, (MqttConnectMessage) message);
                    case PUBLISH:

                        //发布消息
                        return mqttAclFeatures.publishMessage(session, variableHeader, message);
                    case SUBSCRIBE:

                        //客户端订阅请求
                        return mqttAclFeatures.subscribeMessage(session, message, variableHeader);
                    case UNSUBSCRIBE:
                        //客户端取消订阅请求
                        return mqttAclFeatures.unsubscribeMessage(session, message, variableHeader);
                    case DISCONNECT:
                        //客户端断开连接
                        return mqttAclFeatures.disconnectMessage(session, variableHeader);
                    default:
                        return true;
                }
            }

        });
    }
}

